package com.ruoyi.quartz.service.impl;
import com.ruoyi.quartz.config.YamlConfigProperties;
import com.ruoyi.quartz.service.YamlGenerateService;
import com.ruoyi.service.ITtsCameraInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class YamlGenerateServiceImpl implements YamlGenerateService {
    private static final Logger log = LoggerFactory.getLogger(YamlGenerateServiceImpl.class);
    private static  String BASE_DIR;
    private static  String FILE_PREFIX ; // 文件前缀，用于识别需要清理的文件
    private static  String FILE_SUFFIX ; // 文件后缀
    private static  String FILE_HEADER ;
    private static  String MEDIA_PARAMS;
    @Autowired
    private ITtsCameraInfoService ttsCameraInfoService;

    private final YamlConfigProperties yamlConfig;
    @Autowired
    public YamlGenerateServiceImpl(YamlConfigProperties yamlConfig) {
        this.yamlConfig = yamlConfig;
        log.info("YAML 生成服务初始化完成");
        log.info("基础目录: {}", yamlConfig.getBaseDir());
        log.info("文件前缀: {}", yamlConfig.getFilePrefix());
        log.info("文件后缀: {}", yamlConfig.getFileSuffix());
        log.info("生成定时: {}", yamlConfig.getGenerationCron());
        log.info("保留天数: {}", yamlConfig.getRetentionDays());
        BASE_DIR=yamlConfig.getBaseDir();
        FILE_PREFIX=yamlConfig.getFilePrefix();
        FILE_SUFFIX = yamlConfig.getFileSuffix();
        FILE_HEADER = yamlConfig.getFileHeader();
        MEDIA_PARAMS = yamlConfig.getMediaParams();
    }


    @Override
    public Map<String, Object> generateYamlFile() throws IOException {

        File dir = new File(BASE_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
            log.info("创建YAML存储目录：{}", BASE_DIR);
        }
        // 生成带日期时间的新文件名
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String fileName = FILE_PREFIX + sdf.format(new Date()) + FILE_SUFFIX;
//        String filePath = BASE_DIR + FILE_PREFIX;
        String fileName = FILE_PREFIX + FILE_SUFFIX;
        String filePath = BASE_DIR + File.separator + fileName;

        // 准备数据并生成新文件
        Map<String, Object> data = prepareData();
        generateFile(filePath, data);
        // 生成成功后，删除目录中其他旧文件
        deleteOldFiles(dir, fileName);
        Map<String, Object> result = new HashMap<>();
        result.put("status", "SUCCESS");
        result.put("filePath", filePath);
        result.put("message", "YAML文件生成成功，已清理旧文件");
        log.info("YAML文件生成成功，路径：{}", filePath);
        return result;
    }


    /**
     * 生成YAML文件
     */
    private void generateFile(String filePath, Map<String, Object> data) throws IOException {
        DumperOptions options = new DumperOptions();
        options.setIndent(2);
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setPrettyFlow(true);
        Yaml yaml = new Yaml(options);
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(FILE_HEADER);
            writer.write("\n");
            yaml.dump(data, writer);
        }
    }
    /**
     * 删除目录中除最新文件外的其他历史文件
     * @param dir 存储目录
     * @param currentFileName 最新生成的文件名
     */
    private void deleteOldFiles(File dir, String currentFileName) {
        // 获取目录中所有符合命名规则的文件
        File[] files = dir.listFiles((d, name) ->
                name.startsWith(FILE_PREFIX) && name.endsWith(FILE_SUFFIX)
        );
        if (files == null || files.length == 0) {
            log.info("目录中没有需要清理的旧文件");
            return;
        }
        // 遍历并删除非当前文件的旧文件
        for (File file : files) {
            // 跳过当前刚生成的文件
            if (file.getName().equals(currentFileName)) {
                continue;
            }
            // 删除旧文件
            if (file.delete()) {
                log.info("已删除旧文件：{}", file.getAbsolutePath());
            } else {
                log.warn("删除旧文件失败：{}", file.getAbsolutePath());
            }
        }
    }
    @Override
    public Map<String, Object> prepareData() {
        Map<String, Object> data = new HashMap<>();
        Map<String, List<String>> streams = new LinkedHashMap<>();
        List<Map<String, Object>> dbDataList = ttsCameraInfoService.selectTtsCameraInfoListScheduled();
        log.info("查询到 {} 个在线摄像头（按id升序）", dbDataList.size());
        for (Map<String, Object> camera : dbDataList) {
            Object idObj = camera.get("id");
            String camKey;
            if (idObj != null) {
                try {
                    long id = Long.parseLong(idObj.toString());
                    camKey = "cam" + id;
                    log.debug("生成cam键名：{}（id：{}）", camKey, id);
                } catch (NumberFormatException e) {
                    int index = dbDataList.indexOf(camera);
                    camKey = "cam" + (index + 1);
                    log.warn("id不是数字类型（{}），使用索引生成键名：{}", idObj, camKey);
                }
            } else {
                int index = dbDataList.indexOf(camera);
                camKey = "cam" + (index + 1);
                log.warn("摄像头无id，使用索引生成键名：{}", camKey);
            }
            String rtspUrl = "";
            Object rtspObj = camera.get("rtsp");
            if (rtspObj != null) {
                rtspUrl = rtspObj.toString().trim() + MEDIA_PARAMS;
            } else {
                log.warn("{} 的rtsp地址为空", camKey);
            }
            List<String> streamList = new ArrayList<>();
            streamList.add("ffmpeg:" + rtspUrl);
            streams.put(camKey, streamList);
        }
        data.put("streams", streams);
        data.put("recordCount", dbDataList.size());
        return data;
    }
}
